package com.xhy.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhy.entity.VideoVO;
import com.xhy.service.VideoSearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class VideoSearchServiceImpl implements VideoSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Map<String, Object> videos(String q, Integer page, Integer rows) {
        //定义map  total_count 返回查询总数        items: 返回查询记录
        HashMap<String, Object> result = new HashMap<>();
        //计算分页 起始为0
        int start = (page - 1) * rows;
        //创建搜索对象
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder
                .from(start) //从start开始
                .size(rows) //每页显示的rows
                .query(QueryBuilders.matchQuery("title",q)); //term查询条件
        //设置搜索索引video 设置搜索类型video 设置搜索条件
        searchRequest.indices("yingxue").source(sourceBuilder);
        //执行搜索
        SearchResponse search = null;
        try {
            search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //获取符合条件的总数
            long totalHits = search.getHits().getTotalHits().value;
            //获取封装结果
            if (totalHits > 0){
                result.put("total_count",totalHits);
                //获取符合条件的文档数组
                SearchHit[] hits = search.getHits().getHits();
                //创建list集合
                ArrayList<VideoVO> videoVOS = new ArrayList<>();
                for (SearchHit hit : hits) {
                    //10.获取文件字符串表现形式  就是json格式
                    String sourceAsString = hit.getSourceAsString();
                    log.info("符合条件的结果集：{}",sourceAsString);
                    //11.通过jackson将json格式转为videoVo对象
                    VideoVO videoVO = new ObjectMapper().readValue(sourceAsString, VideoVO.class);
                    //设置文档videoVo文档id
                    videoVO.setId(Integer.parseInt(hit.getId()));
                    videoVOS.add(videoVO);
                }
                result.put("items",videoVOS);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
